import 'package:riverpod/riverpod.dart';
import '../models/word.dart';
import '../services/word_service.dart';
import '../services/storage_service.dart';

// 收藏刷新触发器
final starredRefreshProvider = StateProvider<int>((ref) => 0);

final wordServiceProvider = Provider<WordService>((ref) => WordService());

final wordsProvider = FutureProvider.family<List<Word>, String>((ref, category) async {
  final wordService = ref.watch(wordServiceProvider);
  return wordService.getWordsByCategory(category);
});

final searchWordsProvider = FutureProvider.family<List<Word>, String>((ref, query) async {
  final wordService = ref.watch(wordServiceProvider);
  if (query.isEmpty) return [];
  return wordService.searchWords(query);
});

final wordDetailProvider = FutureProvider.family<Word?, String>((ref, wordId) async {
  final wordService = ref.watch(wordServiceProvider);
  return wordService.getWordById(wordId);
});

final favoriteWordsProvider = StateNotifierProvider<FavoriteWordsNotifier, List<String>>((ref) {
  return FavoriteWordsNotifier(ref.watch(storageServiceProvider));
});

class FavoriteWordsNotifier extends StateNotifier<List<String>> {
  final StorageService _storageService;

  FavoriteWordsNotifier(this._storageService) : super([]) {
    _loadFavorites();
  }

  Future<void> _loadFavorites() async {
    final favorites = await _storageService.getFavoriteWords();
    state = favorites;
  }

  Future<void> toggleFavorite(String wordId) async {
    if (state.contains(wordId)) {
      await _storageService.removeFavoriteWord(wordId);
      state = state.where((id) => id != wordId).toList();
    } else {
      await _storageService.addFavoriteWord(wordId);
      state = [...state, wordId];
    }
  }

  bool isFavorite(String wordId) {
    return state.contains(wordId);
  }
} 